/*******************************************************************************
 ** Name: Timer.cpp                                                           **
 ** Description:                                                              **
 **                                                                           **
 ** Open Source Initiative (OSI) Approved 2-clause BSD License                **
 **                                                                           **
 **  Copyright (c) 2009-2010 Barry "Gian" James  <bjames@munixos.net>         **
 **  All rights reserved.                                                     **
 **                                                                           **
 **  Redistribution and use in source and binary forms, with or without       **
 **  modification, are permitted provided that the following conditions are   **
 **  met:                                                                     **
 **                                                                           **
 **  * Redistributions of source code must retain the above copyright notice, **
 **    this list of conditions and the following disclaimer.                  **
 **  * Redistributions in binary form must reproduce the above copyright      **
 **    notice, this list of conditions and the following disclaimer in the    **
 **    documentation and/or other materials provided with the distribution.   **
 **                                                                           **
 **  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS      **
 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED **
 ** TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A           **
 ** PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT        **
 ** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,    **
 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED  **
 ** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR    **
 ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    **
 ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      **
 ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        **
 ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              **
 **                                                                           **
 ******************************************************************************/
// Created on March 16, 2010, 9:45 PM
// Modified $Date: 2011-10-22 02:09:07 +0000 (Sat, 22 Oct 2011) $ by $Author: gian.james $
#define  Timer_cpp_ID    "$Id: timer.cpp 146 2011-10-22 02:09:07Z gian.james $"

extern "C" {
#include <unistd.h>	// alarm()
#include <string.h> // strerror()
}
#include <iostream>
#include "timer.hpp"
#include "log.hpp"

void DefaultSignalHandler(int signo,siginfo_t * evp,void * ucontext)
{
	std::cerr << "Timer ID: " << evp->si_timerid << " PID: " << evp->si_pid << std::endl;
	std::cerr << "Signal #: " << signo << " UID: " << evp->si_uid << std::endl;
	ucontext_t * uc = reinterpret_cast<ucontext_t*>(ucontext);
//	std::cerr << "ucontext_t flags: " << std::hex << uc->uc_flags << " Sigmask: " << uc->uc_sigmask << std::endl;
}	// TODO fix line above

//////////////////////////////////////[ TimeManager
MonthStrings
TimeManager::monthName[] = {
	{ "January", "Jan" },
	{ "February", "Feb" },
	{ "March", "Mar" },
	{ "April", "Apr" },
	{ "May", "May" },
	{ "June", "Jun" },
	{ "July", "Jul" },
	{ "August", "Aug" },
	{ "September", "Sept" },
	{ "October", "Oct" },
	{ "November", "Nov" },
	{ "December", "Dec" },
	{ NULL, NULL }
};
const char * TimeofDayStr[] = {
		"The sun is just rising above the horizon with a faint glow.",
		"The day has begun.",
		"It's now high noon.",
		"The sun is slow setting on the horizon in splashes of red and yellow.",
		"Nighttime has officially begun.",
		"It's midnight, the witching hour.",
		NULL
};

TimeManager::TimeManager(int m, int h, int d, int mo, int y)
{
	timeInfo.min = m;
	timeInfo.hour = h;
	timeInfo.day = d;
	timeInfo.month = mo;
	timeInfo.year = y;
}
const char *
TimeManager::DiscordianDate(const char * fmt, bool kb, bool pb)
{

	return NULL;
}
const char *
TimeManager::DaySuffix(int day)
{
	const char * suffix;
	if (day > 4 && day < 20) suffix = "th";
	else if (day % 10 == 1) suffix = "st";
	else if (day % 10 == 2) suffix = "nd";
	else if (day % 10 == 3) suffix = "rd";
	else suffix = "th";
}
int
TimeManager::IncrMin()
{
	if (++timeInfo.min ==60)
	{
		timeInfo.min == 0;
		IncrHour();
	}
	return timeInfo.min;
}

int
TimeManager::IncrHour()
{
	if (++timeInfo.hour == 24)
	{
		timeInfo.hour = 0;
		IncrDay();
	}
	// TODO fire TimeofHour event for hour event listeners
	return timeInfo.hour;
}

int
TimeManager::IncrDay()
{
	if (++timeInfo.day == 31)
	{
		timeInfo.day = 1;
		IncrMonth();
	}
	return timeInfo.day;
}

int
TimeManager::IncrMonth()
{
	if (++timeInfo.month == 13)
	{
		timeInfo.month = 1;
		IncrYear();
	}
	// TODO fire event for new month to let items like loans
	// update their values
	return timeInfo.month;
}

int
TimeManager::IncrYear()
{
	++timeInfo.year;
	// TODO fire newyearevent to let eventlisteners take action
	return timeInfo.year;
}
//////////////////////////////////////[ Timer
int
Timer::_id = 0;

tm *
Timer::TimeDelta(bool bLocalTime, time_t t1, time_t t2)
{
	time_t delta = t2 - t1;
	if (bLocalTime) return localtime(&delta);
	else return gmtime(&delta);
}


int
Timer::Remaining(long & sec, long & nsec)
{
	if (status != TIMER_OK) return TIMER_ERROR;
	if (timer_gettime(handle,&spec) == -1) {
		status = errno;
		char buff[256];
		strerror_r(errno,buff,256);
		debug::log->out(LOG_CRIT,"timer_gettime(%d): %s",errno,buff);
		return TIMER_ERROR;
	}
	sec		= spec.it_value.tv_sec;
	nsec	= spec.it_value.tv_nsec;

	return TIMER_OK;
}

long
Timer::Elapsed()
{
	return TIMER_ERROR;
}

int
Timer::Run(long startSec, long startNSec, long reloadSec, long reloadNSec)
{
	if (status != TIMER_OK) return TIMER_ERROR;

	spec.it_value.tv_sec	= startSec;
	spec.it_value.tv_nsec	= startNSec;
	spec.it_interval.tv_sec	= reloadSec;
	spec.it_interval.tv_nsec= reloadNSec;

	if (timer_settime(handle,0,&spec,0) == -1) {
		status = errno;
		char buff[256];
		strerror_r(errno,buff,256);
		debug::log->out(LOG_CRIT,"timer_settime(%d): %s",errno,buff);
		return TIMER_ERROR;
	}
	return TIMER_OK;
}

int
Timer::Run(time_t startTime, long reloadSec, long reloadNSec)
{
	if (status != TIMER_OK) return TIMER_ERROR;

	spec.it_value.tv_sec	= startTime;
	spec.it_value.tv_nsec	= 0;
	spec.it_interval.tv_sec	= reloadSec;
	spec.it_interval.tv_nsec= reloadNSec;

	if (timer_settime(handle,TIMER_ABSTIME,&spec,0) == -1) {
		status = errno;
		char buff[256];
		strerror_r(errno,buff,256);
		debug::log->out(LOG_CRIT,"timer_settime(%d): %s",errno,buff);
		return TIMER_ERROR;
	}
	return TIMER_OK;

}

int
Timer::Stop()
{
	if (status != TIMER_OK) return TIMER_ERROR;

	spec.it_value.tv_sec	= 0;
	spec.it_value.tv_nsec	= 0;
	spec.it_interval.tv_sec	= 0;
	spec.it_interval.tv_nsec= 0;

	if (timer_settime(handle,0,&spec,0) == -1) {
		status = errno;
		char buff[256];
		strerror_r(errno,buff,256);
		debug::log->out(LOG_CRIT,"timer_settime(%d): %s",errno,buff);
		return TIMER_ERROR;
	}
	return TIMER_OK;
}

int
Timer::Overrun()
{
	if (status != TIMER_OK) return TIMER_ERROR;
	return timer_getoverrun(handle);
}

void
Timer::Alarm(int sec)
{
    alarm(sec);
}

//! signum = signal to raise, action = signal handler
//! timerID = this timer's ID, clock = type of system clock
Timer::Timer(int signum, sigFunc action, int timerID, clock_t clock)
{
	timerID = incr();
	status = TIMER_OK;
	struct sigaction sigv;

	sigemptyset(&sigv.sa_mask);
	sigv.sa_flags = SA_SIGINFO;	// so we can use our sigFunc
	sigv.sa_sigaction = action;

	if (sigaction(signum,&sigv,0) == -1) {
		status = errno;
		char buff[256];
		strerror_r(errno,buff,256);
		debug::log->out(LOG_CRIT,"sigaction(%d): %s",errno,buff);
	} else {
		sigevent sigx;
		sigx.sigev_notify	= SIGEV_SIGNAL;
		sigx.sigev_signo	=  signum;
		sigx.sigev_value.sival_int = timerID;

		if (timer_create(clock,&sigx,&handle) == -1) {
			status = errno;
			char buff[256];
			strerror_r(errno,buff,256);
			debug::log->out(LOG_CRIT,"timer_create(%d): %s",errno,buff);
		}
	}
}

Timer::~Timer()
{
	if (status == TIMER_OK) {
		Stop();
		if (timer_delete(handle) == -1) {
			char buff[256];
			strerror_r(errno,buff,256);
			debug::log->out(LOG_CRIT,"timer_delete(%d): %s",errno,buff);
		}
	}
}

// TODO fix
//std::ostream &
//Timer::operator << (std::ostream & o, const Timer & t)
//{
//	long sec, nsec;
//	t.Remaining(sec,nsec);
//	double tval = sec + ((double)nsec/1000000000.0);
//	o << "Time remaining: " << tval << std::endl;
//	return o;
//}

